public class Solution {
    public static void main(String[] args) {
       int[] height = {4,2,0,3,2,5};
        System.out.println(trap(height));
    }
    //接雨水
    public static int trap(int[] height) {
        //找到最长的柱子，计算左右两边接水总量
        int max_index = 0;
        int max = 0;
        int n = height.length;
        for(int i = 0; i < n; i++) {
            if(height[i] > max) {
                max = height[i];
                max_index = i;
            }
        }
        //计算左边的接水量
        int left_sum = 0;
        int left_cur_max = 0;
        for(int i = 0; i < max_index; i++) {
            left_cur_max = height[i] > left_cur_max ? height[i] : left_cur_max;
            left_sum = left_sum + left_cur_max - height[i];
        }
        //计算右边接水量
        int right_sum = 0;
        int right_cur_max = 0;
        for(int i = n-1; i > max_index; i--) {
            right_cur_max = height[i] > right_cur_max ? height[i] : right_cur_max;
            right_sum = right_sum + right_cur_max - height[i];
        }
        return left_sum+right_sum;
    }
}
